package com.gxb.codebook;

import android.Manifest;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.CancellationSignal;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

@RequiresApi(api = Build.VERSION_CODES.M)
public class FingerprintLogin {
    private FragmentActivity mActivity;
    private AuthenticationCallback mCallback;
    private Dialog mDialog;
    private FingerprintManager mFingerprintManager;
    private KeyguardManager mKeyguardManager;
    private CancellationSignal mCancellationSignal;
    private boolean isAuthenticating = false;
    private boolean isCanceled = false;
    private LocalBroadcastManager localBroadcastManager;
    private BroadcastReceiver fingerprintBroadcastReceiver;

    public interface AuthenticationCallback {
        void onAuthenticationResult(boolean success);
    }

    public boolean isAuthenticating() {
        return isAuthenticating;
    }

    public FingerprintLogin(FragmentActivity activity, AuthenticationCallback callback) {
        this.mActivity = activity;
        this.mCallback = callback;
        initializeFingerprintManager();
        initializeBroadcast();
    }

    private void initializeFingerprintManager() {
        mFingerprintManager = (FingerprintManager) mActivity.getSystemService(Context.FINGERPRINT_SERVICE);
        mKeyguardManager = (KeyguardManager) mActivity.getSystemService(Context.KEYGUARD_SERVICE);
    }

    private void initializeBroadcast() {
        // 初始化LocalBroadcastManager
        localBroadcastManager = LocalBroadcastManager.getInstance(mActivity);

        // 创建广播接收器
        fingerprintBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if ("FINGERPRINT_AUTH_REQUEST".equals(action)) {
                    // 收到指纹验证请求的广播
                    authenticate();
                } else if ("FINGERPRINT_AUTH_CANCEL".equals(action)) {
                    // 收到取消指纹验证的广播
                    cancelAuthentication();
                }
            }
        };

        // 注册广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction("FINGERPRINT_AUTH_REQUEST");
        filter.addAction("FINGERPRINT_AUTH_CANCEL");
        localBroadcastManager.registerReceiver(fingerprintBroadcastReceiver, filter);
    }

    public void authenticate() {
        if (isAuthenticating) {
            return;
        }

        if (!checkFingerprintAvailable()) {
            Toast.makeText(mActivity, "生物识别不可用", Toast.LENGTH_SHORT).show();
            return;
        }

        isAuthenticating = true;
        isCanceled = false;
        showFingerDialog();
    }

    private boolean checkFingerprintAvailable() {
        if (!mFingerprintManager.isHardwareDetected()) {
            Toast.makeText(mActivity, "您的设备不支持指纹识别", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!mKeyguardManager.isKeyguardSecure()) {
            Toast.makeText(mActivity, "请先设置锁屏密码", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(mActivity, "没有指纹识别权限", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!mFingerprintManager.hasEnrolledFingerprints()) {
            Toast.makeText(mActivity, "请先录入指纹", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private void showFingerDialog() {
        mDialog = new Dialog(mActivity);
        mDialog.setContentView(R.layout.dialog_fingerprint);
        mDialog.setCancelable(false);

        if (mDialog.getWindow() != null) {
            mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        }

        Button cancelButton = mDialog.findViewById(R.id.dialog_cancel);

        cancelButton.setOnClickListener(v -> {
            isCanceled = true;
            cancelAuthentication();
        });

        mDialog.setOnDismissListener(dialog -> {
            if (!isCanceled) {
                cancelAuthentication();
            }
        });

        mDialog.show();
        startFingerprintAuthentication();
    }

    private void startFingerprintAuthentication() {
        if (mCancellationSignal == null) {
            mCancellationSignal = new CancellationSignal();
        }

        if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
            resetAuthenticationState();
            return;
        }

        try {
            mFingerprintManager.authenticate(
                    null,
                    mCancellationSignal,
                    0,
                    new FingerprintManager.AuthenticationCallback() {
                        @Override
                        public void onAuthenticationError(int errorCode, CharSequence errString) {
                            mActivity.runOnUiThread(() -> {
                                if (errorCode == FingerprintManager.FINGERPRINT_ERROR_CANCELED) {
                                    return; // 忽略主动取消的错误
                                }
                                Toast.makeText(mActivity, errString, Toast.LENGTH_SHORT).show();
                                resetAuthenticationState();

                                // 发送验证失败的广播
                                Intent intent = new Intent("FINGERPRINT_AUTH_RESULT");
                                intent.putExtra("success", false);
                                localBroadcastManager.sendBroadcast(intent);
                            });
                        }

                        @Override
                        public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
                            // 不需要处理帮助信息
                        }

                        @Override
                        public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
                            mActivity.runOnUiThread(() -> {
                                Toast.makeText(mActivity, "身份验证成功!", Toast.LENGTH_SHORT).show();
                                handleAuthenticationResult(true);

                                // 发送验证成功的广播
                                Intent intent = new Intent("FINGERPRINT_AUTH_RESULT");
                                intent.putExtra("success", true);
                                localBroadcastManager.sendBroadcast(intent);
                            });
                        }

                        @Override
                        public void onAuthenticationFailed() {
                            mActivity.runOnUiThread(() -> {
                                // 不需要显示失败提示，等待用户重试
                            });
                        }
                    },
                    null
            );
        } catch (SecurityException e) {
            mActivity.runOnUiThread(() -> {
                Toast.makeText(mActivity, "安全异常: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                resetAuthenticationState();

                // 发送验证失败的广播
                Intent intent = new Intent("FINGERPRINT_AUTH_RESULT");
                intent.putExtra("success", false);
                localBroadcastManager.sendBroadcast(intent);
            });
        }
    }

    private void handleAuthenticationResult(boolean success) {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
        if (mCallback != null) {
            mCallback.onAuthenticationResult(success);
        }
        resetAuthenticationState();
    }

    private void cancelAuthentication() {
        if (mCancellationSignal != null && !mCancellationSignal.isCanceled()) {
            mCancellationSignal.cancel();
        }
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
        resetAuthenticationState();
    }

    private void resetAuthenticationState() {
        isAuthenticating = false;
        isCanceled = false;
        mCancellationSignal = null;
    }

    // 添加一个方法来释放资源
    public void release() {
        if (localBroadcastManager != null && fingerprintBroadcastReceiver != null) {
            localBroadcastManager.unregisterReceiver(fingerprintBroadcastReceiver);
        }
    }
}
